package 华为OD机试真题2023.进阶题;

import utils.MyUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class HJ25_机器人活动区域 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner in = new Scanner(new File("src/main/java/华为OD机试真题2023/进阶题/input/25.txt"));
        MyUtil.START();
        Solution(in);
        MyUtil.END();
    }

    static int[][] matrix;
    static boolean[][] visited;
    static int max = 1, row, column, tmpCount;

    static void Solution(Scanner in) {
        row = in.nextInt();
        column = in.nextInt();
        matrix = new int[row][column];
        visited = new boolean[row][column];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                matrix[i][j] = in.nextInt();
            }
        }
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                if (!visited[i][j]) {
                    tmpCount = 0;
                    dfs(i, j, matrix[i][j]);
                }
            }
        }
        System.out.println(max);
    }

    static void dfs(int x, int y, int before) {
        if (x < 0 || x >= row || y < 0 || y >= column || visited[x][y]) {
            return;
        }
        int now = matrix[x][y];
        if (Math.abs(now - before) <= 1) {
            visited[x][y] = true;
            tmpCount++;
            max = Math.max(max, tmpCount);
        } else {
            return;
        }
        dfs(x - 1, y, now); // 上
        dfs(x + 1, y, now); // 下
        dfs(x, y - 1, now); // 左
        dfs(x, y + 1, now); // 右
    }
}
